package io.zhengsh.juc._1aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CyclicBarrierTest {
    // 线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
    // 限制只有 5 个线程能够同时获取锁
    private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

    public static void main(String[] args) throws InterruptedException {
        // 场景，10 个线程，有序的获取共享锁
        log.info("main 开始执行");
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            executorService.submit(() -> exec());
        }
    }

    // 执行逻辑
    public static void exec() {
        try {
            log.info("exec 方法就绪");
            cyclicBarrier.await(); //阻塞
            log.info("执行 exec 方法");
            TimeUnit.SECONDS.sleep(2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
